const vscode = require("vscode");
module.exports = {
  name: "formatArticle",
  implementation: function () {
    let editBehaviorHandler = {
      queue: [],
      add(opt, ...args) {
        this.queue.push({
          opt,
          args,
        });
      },
      emit() {
        const editor = vscode.window.activeTextEditor;
        editor.edit((editBuilder) => {
          this.queue.forEach((edit) => {
            let { opt, args } = edit;
            editBuilder[opt](...args);
          });
          vscode.window.showInformationMessage("edit-article格式化完成");
        });
      },
    };
    let replaceItems = [
      {
        oldText: /([\u4e00-\u9fa5]+)([\da-zA-Z]+)/,
        newText(matchResult) {
          let [, $1, $2] = matchResult;
          return `${$1} ${$2}`;
        },
      },
      {
        oldText: /([\da-zA-Z]+)([\u4e00-\u9fa5]+)/,
        newText(matchResult) {
          let [, $1, $2] = matchResult;
          return `${$1} ${$2}`;
        },
      },
      {
        oldText: /!\[.+\]/,
        newText: "![]",
      },
    ];
    const replaceText = (oldText, newText) => {
      const editor = vscode.window.activeTextEditor;
      const document = editor.document;
      const documentText = document.getText();
      if (!editor) {
        return;
      }
      let replaceStatements = [];
      // 检测console的正则表达式
      const textRegex = new RegExp(oldText, "g");
      let match;
      // 正则循环匹配页面文本
      while ((match = textRegex.exec(documentText))) {
        // 每次匹配到当前的范围--Range
        let matchRange = new vscode.Range(
          document.positionAt(match.index),
          document.positionAt(match.index + match[0].length)
        );
        if (!matchRange.isEmpty)
          // 把Range放入数组
          replaceStatements.push({
            range: matchRange,
            newText: typeof newText === "function" ? newText(match) : newText,
          });
      }
      // 循环遍历每个匹配项的range，并删除
      replaceStatements.forEach((replaceItem) => {
        let { range, newText } = replaceItem;
        editBehaviorHandler.add("replace", range, newText);
      });
    };
    replaceItems.forEach((replaceItem) => {
      let { oldText, newText } = replaceItem;
      replaceText(oldText, newText);
    });
    const insertText = (val, line = 0, startCharacter = 0) => {
      // edit方法获取editBuilder实例，在后一行添加
      let startLine = line;

      editBehaviorHandler.add(
        "insert",
        new vscode.Position(startLine, startCharacter),
        val
      );
    };
    insertText(`---
theme: cyanosis
highlight: atom-one-dark
---
> 王志远，微医前端技术部
`);
    editBehaviorHandler.emit();
  },
};
